import { NestFactory } from '@nestjs/core';
import { AppModule } from './app/app.module';
import { setup } from '@dui/node-http-cls-express';
import { Logger } from '~/common/service/logger.service';
import responseTime from 'response-time';
import { Request, Response } from 'express';
import { getLogger } from '@dui/node-logger';

const cors = require('cors');
const cookieParser = require('cookie-parser');

const accessLogMiddleware = responseTime(
  (req: Request, res: Response, time) => {
    const latency = Math.round(time);
    getLogger().info(
      {
        type: 'access',
        method: req.method,
        url: req.url,
        latency: latency,
        userAgent: req.headers['user-agent'],
        statusCode: res.statusCode,
      },
      '%s %s %dms %d',
      req.method,
      req.url,
      time,
      res.statusCode
    );
  }
);

const port = parseInt(process.env.PORT, 10) || 3101;

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { logger: new Logger() });
  setup(app as any);
  // app.use(accessLogMiddleware);
  app.use(cors())
  app.use(cookieParser());
  await app.listen(port);
}

bootstrap();
